package gw.com.android.ui.me;

import android.graphics.Typeface;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gwtsz.android.rxbus.SimpleObserver;
import com.gwtsz.gts2.hx.R;

import java.text.NumberFormat;
import java.util.Locale;

import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.greendao.NotifyDataHelper;
import gw.com.android.model.ConfigSettingDeal;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.AdsConfigPresenter;
import gw.com.android.presenter.AdsData;
import gw.com.android.presenter.LoginPresenter;
import gw.com.android.presenter.PresenterImpl;
import gw.com.android.presenter.SwitchAccountPresenter;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.MainActivity;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.views.FloatAdverView;
import gw.com.android.utils.PackStatis;
import gw.com.android.utils.PayegisUtil;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import www.com.library.app.Logger;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.CommonUtils;
import www.com.library.util.NetworkMonitor;
import www.com.library.view.BtnClickListener;

/**
 * 我  的 首页
 *
 * @author jett
 * @since 2018-11-29.
 */
public class MineFragment extends PushMsgTabFragment implements View.OnClickListener, PresenterImpl {

    private TextView tvUsername;
    private TextView tvSwitch;
    private View viewTag;
    private View viewCertification;
    private View viewAssetPanel;
    private TextView tvAsset;
    private TextView tvSymbol;
    private TextView tvAmount;
    private ImageView ivEye;
    private View viewFunctions, viewFunction1, viewFunction2;
    private ImageView ivFunc1Icon, ivFunc2Icon;
    private TextView tvFunc1Text, tvFunc2Text;
    private ImageView ivAd;
    private View viewDivider;
    private FloatAdverView mFloatAds;

    private RecyclerView mListView;
    private MineAdapter mAdapter;
    private LoginPresenter mPresenter;
    private SwitchAccountPresenter mSwitchPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initLayoutView() {
        mListView = mRootView.findViewById(R.id.mine_list);
        mFloatAds = mRootView.findViewById(R.id.mine_float_ad);
        View headerView = View.inflate(getContext(), R.layout.fragment_mine_header, null);
        View footerView = View.inflate(getContext(), R.layout.fragment_mine_footer, null);
        footerView.findViewById(R.id.mine_service).setOnClickListener(this);
        tvUsername = headerView.findViewById(R.id.mine_username);
        tvSwitch = headerView.findViewById(R.id.mine_switch);
        viewTag = headerView.findViewById(R.id.mine_tag);
        viewCertification = headerView.findViewById(R.id.mine_certification);
        viewAssetPanel = headerView.findViewById(R.id.mine_asset_panel);
        tvAsset = headerView.findViewById(R.id.mine_asset);
        tvSymbol = headerView.findViewById(R.id.mine_symbol);
        tvAmount = headerView.findViewById(R.id.mine_amount);
        ivEye = headerView.findViewById(R.id.mine_eye);
        viewFunctions = headerView.findViewById(R.id.mine_function);
        viewFunction1 = headerView.findViewById(R.id.mine_function1);
        viewFunction2 = headerView.findViewById(R.id.mine_function2);
        ivFunc1Icon = headerView.findViewById(R.id.mine_function1_icon);
        tvFunc1Text = headerView.findViewById(R.id.mine_function1_text);
        ivFunc2Icon = headerView.findViewById(R.id.mine_function2_icon);
        tvFunc2Text = headerView.findViewById(R.id.mine_function2_text);
        ivAd = headerView.findViewById(R.id.mine_center_ad);
        viewDivider = headerView.findViewById(R.id.mine_header_divider);
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
            tvSwitch.setVisibility(View.GONE);
            tvSymbol.setVisibility(View.GONE);
            ivEye.setVisibility(View.GONE);
        }

        Typeface font = Typeface.createFromAsset(getResources().getAssets(), "fonts/DIN_Medium.ttf");
        tvSymbol.setTypeface(font);
        tvAmount.setTypeface(font);
        mAdapter = new MineAdapter(getActivity(), this);
        mAdapter.setHeaderView(headerView);
        mAdapter.setFooterView(footerView);
        BaseActivity activity = (BaseActivity) getActivity();
        if (null != activity) {
            activity.setTransparentBar(true);
        }
    }

    @Override
    protected void initViewData() {
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
            viewAssetPanel.setBackgroundResource(R.mipmap.a_me_bg1);
            tvUsername.setText(R.string.me_guest_name);
            tvAsset.setText(R.string.me_asset);
            tvSymbol.setVisibility(View.GONE);
            tvAmount.setText("----");
            ivFunc1Icon.setImageResource(R.mipmap.a_me_login);
            tvFunc1Text.setText(R.string.system_title_tourist_login);
            ivFunc2Icon.setImageResource(R.mipmap.a_me_gift);
            tvFunc2Text.setText(R.string.system_title_tourist_openAcc);
        } else {
            if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_DEMO) {
                viewAssetPanel.setBackgroundResource(R.mipmap.a_me_bg2);
                viewFunctions.setVisibility(View.GONE);
                viewDivider.setVisibility(View.GONE);
                tvAsset.setText(R.string.me_asset_demo);
                tvSwitch.setText(R.string.me_switch_real);
            } else {
                viewAssetPanel.setBackgroundResource(R.mipmap.a_me_bg1);
                tvAsset.setText(R.string.me_asset);
                tvSwitch.setText(R.string.me_switch_demo);
                ivFunc1Icon.setImageResource(R.mipmap.a_me_withdraw);
                tvFunc1Text.setText(R.string.me_withdraw);
                ivFunc2Icon.setImageResource(R.mipmap.a_me_recharge);
                tvFunc2Text.setText(R.string.me_deposit);
                //tvFunc2Text.setTextColor(getResources().getColor(R.color.color_u));
            }
            showBalance(GTConfig.instance().getBooleanValue(GTConfig.PREF_ASSET_SHOW, true));
        }

        tvSwitch.setOnClickListener(this);
        viewTag.setOnClickListener(this);
        viewCertification.setOnClickListener(this);
        ivEye.setOnClickListener(this);
        viewFunction1.setOnClickListener(this);
        viewFunction2.setOnClickListener(this);

        DataItemResult mineList = ConfigSettingDeal.getMineList();
        mAdapter.setDatas(mineList);
        mListView.setLayoutManager(new LinearLayoutManager(getContext()));
        mListView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
        onSendQuote();

        refreshMeAds();
        requestCertification();
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                e.onNext(NotifyDataHelper.getUnreadCount());
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new SimpleObserver<Integer>() {
            @Override
            public void onNext(Integer result) {
                refreshRedPoint(result);
            }
        });
    }

    /**
     * 显示余额
     */
    private void showBalance(boolean show) {
        if (ivEye != null && tvAmount != null && GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_GUEST) {
            boolean hasAccount = DataManager.instance().hasAccount();
            if (show) {
                ivEye.setImageResource(R.mipmap.a_me_eye_moninvisible);
                tvSymbol.setText(hasAccount ? "$" : "");
                tvAmount.setText(hasAccount ? getBalance() : "--");
            } else {
                ivEye.setImageResource(R.mipmap.a_me_eye_monvisible);
                tvSymbol.setText("");
                tvAmount.setText(hasAccount ? "****" : "--");
            }
            if (TextUtils.isEmpty(GTConfig.instance().mCurName)) {
                GTConfig.instance().mCurName = DataManager.instance().mAccount.getString(GTSConst.JSON_KEY_NAME);
            }
            if (!TextUtils.isEmpty(GTConfig.instance().mCurName)) {
                tvUsername.setText(GTConfig.instance().mCurName);
            }
        }
    }

    /**
     * 获取格式化的余额
     */
    private String getBalance() {
        String amount = DataManager.instance().mAccount.getString(GTSConst.JSON_KEY_BALANCE);
        try {
            double balance = Double.valueOf(amount);
            return NumberFormat.getNumberInstance(Locale.getDefault()).format(balance);
        } catch (Throwable t) {
            return amount;
        }
    }

    public void refreshRedPoint(int count) {
        if (mAdapter != null) {
            mAdapter.setUnReadCount(count);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onAccountNotify() {
        super.onAccountNotify();
        showBalance(GTConfig.instance().getBooleanValue(GTConfig.PREF_ASSET_SHOW, true));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isHidden()) {
            BaseActivity activity = (BaseActivity) getActivity();
            if (null != activity) {
                activity.setTransparentBar(true);
            }
            onSendQuote();
            showBalance(GTConfig.instance().getBooleanValue(GTConfig.PREF_ASSET_SHOW, true));
        }
    }

    @Override
    public void onSendQuote() {
        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCode(0));
    }

    public void refreshMeAds() {
        if (getContext() == null || mListView == null) {
            return;
        }
        // 浮动广告
        AdsData floatAd = AdsConfigPresenter.getInstance().getAd(AdsConfigPresenter.TYPE_HOME_FLOAT);
        mFloatAds.refresh(getActivity(), floatAd, FloatAdverView.INDEX_MINE);
        //  福利小弹窗广告
        AdsData ad = AdsConfigPresenter.getInstance().getAd(AdsConfigPresenter.TYPE_ME_MENU);
        if (ad != null && ad.adPics != null && !ad.adPics.isEmpty()) {
            final AdsData.PicData data = ad.adPics.get(0);
            if (data == null || TextUtils.isEmpty(data.url)) {
                return;
            }
            viewDivider.setVisibility(View.GONE);
            ivAd.setVisibility(View.VISIBLE);
            Glide.with(getActivity()).load(data.url).into(ivAd);
            ivAd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DataItemDetail detail = new DataItemDetail();
                    detail.setStringValue(ConfigType.CONFIG_TYPE_TYPE_URL_TAG, data.link);
                    detail.setStringValue(ConfigType.CONFIG_TYPE_TITLE_TAG, data.title);
                    ActivityManager.showWebPageActivity(getActivity(), detail, null);
                }
            });
        }
    }

    /**
     * 请求 当前账户是否已经通过认证
     */
    private void requestCertification() {
        if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_REAL) {
            return;
        }
        UploadedFileStatus.getInstance().request(GTConfig.instance().mCurName, new UploadedFileStatus.OnStateListener() {
            @Override
            public void onResponse(final boolean approved) {//这个返回值 true表示已认证，false表示未认证
                viewTag.setVisibility(approved ? View.GONE : View.VISIBLE);
                viewCertification.setVisibility(approved ? View.GONE : View.VISIBLE);
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) tvSwitch.getLayoutParams();
                params.gravity = approved ? Gravity.RIGHT | Gravity.CENTER_VERTICAL : Gravity.RIGHT | Gravity.BOTTOM;
                tvSwitch.setLayoutParams(params);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mine_switch:
                switchAccount();
                break;
            case R.id.mine_eye:
                clickEye();
                break;
            case R.id.mine_tag:
            case R.id.mine_certification:
                requestCertification();
                //实名制H5的跳转链接
                DataItemDetail item = new ConfigSettingDeal().getItemValue(ConfigType.MY_BANK_INFO_TAG);
                item.setStringValue(ConfigType.CONFIG_TYPE_TITLE_TAG, "实名认证");
                ActivityManager.showWebPageActivity(getActivity(), item, null);
                break;
            case R.id.mine_function1:
                clickFunction1();
                break;
            case R.id.mine_function2:
                clickFunction2();
                break;
            case R.id.mine_service:
                PackStatis.getToService("clickService", "Me", null, null);
                new ConfigSettingDeal().openQQ(getActivity(), ConfigType.QQ_SOURCE_ME);
                break;
            default:
                break;
        }
    }

    private void goLogin() {
        PackStatis.getToService("clickLogin", PackStatis.EventCategory.ME.getValue(), null, null);
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
            GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
            ActivityManager.backLogin(getActivity(), false);
        }
    }

    private void clickEye() {
        if (!DataManager.instance().hasAccount()) {
            return;
        }
        boolean showAsset = GTConfig.instance().getBooleanValue(GTConfig.PREF_ASSET_SHOW, true);
        showBalance(!showAsset);
        if (!showAsset) {
            PackStatis.getToService(PackStatis.EventAction.CLICKEYE.getValue(), PackStatis.EventCategory.ME.getValue(), null, "2");
        } else {
            PackStatis.getToService(PackStatis.EventAction.CLICKEYE.getValue(), PackStatis.EventCategory.ME.getValue(), null, "1");
        }
        GTConfig.instance().setBooleanValue(GTConfig.PREF_ASSET_SHOW, !showAsset);
    }

    private void switchAccount() {
        if (!NetworkMonitor.hasNetWork()) {
            return;
        }
        if (CommonUtils.isFastDoubleClick()) {
            return;
        }
        mSwitchPresenter = new SwitchAccountPresenter(getActivity(), this);
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_REAL) {
            PackStatis.getToService("clickToDemo", "Me", null, null);
            mSwitchPresenter.AccAccountSwitch(GTConfig.ACC_TYPE_DEMO, GTConfig.FROM_QUOTE);
        } else {
            PackStatis.getToService("clickToReal", "Me", null, null);
            mSwitchPresenter.AccAccountSwitch(GTConfig.ACC_TYPE_REAL, GTConfig.FROM_QUOTE);
        }
    }

    private void clickFunction1() {
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {//游客状态下，左边的按钮是登录
            PackStatis.getToService(PackStatis.EventAction.CLICKLOGIN.getValue(), PackStatis.EventCategory.ME.getValue(), null, null);
            goLogin();
        } else {//非 游客状态下，左边是提现
            PackStatis.getToService(PackStatis.EventAction.CLICKOUTCOME.getValue(), PackStatis.EventCategory.ME.getValue(), null, null);
            DataItemDetail mWithdrawDetail = new ConfigSettingDeal().getItemValue(ConfigType.DRAW_TAG);
            ActivityManager.showWebPageActivity(getActivity(), mWithdrawDetail, AppMain.getAppString(R.string.btn_back));
        }
    }

    private void clickFunction2() {
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {//游客状态下，右边的按钮是开户
            PackStatis.getToService(PackStatis.EventAction.CLICKREG.getValue(), PackStatis.EventCategory.ME.getValue(), null, null);
            ActivityManager.showOpenAccount(getActivity(), ConfigType.ADD_LOGIN_REAL_TAG);
        } else {//非 游客状态下，右边是充值
            PayegisUtil.trackEvent("deposit");
            PackStatis.getToService(PackStatis.EventAction.CLICKINCOME.getValue(), PackStatis.EventCategory.ME.getValue(), null, null);
            DataItemDetail mDepositDetail = new ConfigSettingDeal().getItemValue(ConfigType.DEPOSIT_TAG);
            ActivityManager.showWebPageActivity(getActivity(), mDepositDetail, AppMain.getAppString(R.string.btn_back));
        }
    }

    @Override
    public void onRequestSuc(Object result) {
        if (!isVisible()) {
            Logger.e("切换账号 isVisible is false");
            return;
        } else {
            Logger.e("切换账号 isVisible is true");
        }
        final MainActivity mainActivity = (MainActivity) getActivity();
        if (mainActivity != null) {
            mainActivity.hideLoading();
            mainActivity.removeAllFragment(false, true);
            AppMain.getApp().getHandler().post(new Runnable() {
                @Override
                public void run() {
                    mainActivity.showMeFragment();
                }
            });
        } else {
            Logger.e("切换账号 getActivity() is null");
        }
        AppTerminal.instance().setLoginView(0);
        if (null != mPresenter) {
            mPresenter.isLoading = false;
            mPresenter.setPresenterImpl(null);
            mPresenter = null;
        }
        if (null != mSwitchPresenter) {
            mSwitchPresenter.clearData();
            mSwitchPresenter = null;
        }
    }

    @Override
    public void onRequestFail(int failCode) {
        final BaseActivity mActivity = (BaseActivity) getActivity();
        if (null != mActivity) {
            mActivity.hideLoading();
            if (failCode == 1 || failCode == 34) {
                return;
            }
            String error;
            if (failCode >= 1100 && failCode < 1200) {
                error = ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1100) + failCode;
            } else {
                error = ConfigUtil.instance().getErrorConfigObject().optString(failCode + "");
            }
            PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(mActivity, error, new BtnClickListener() {
                @Override
                public void onBtnClick(int viewID) {
                    GTConfig.instance().isPhoneLogin = false;
                    GTConfig.instance().mCurLoginPhone = "";
                    ActivityManager.backLogin(mActivity, true);
                }
            });
            dialog.setCancelable(false);
            dialog.show();
        }
        if (null != mPresenter) {
            if (GTConfig.instance().getBooleanValue(GTConfig.PREF_AUTO_LOGIN)) {
                GTConfig.instance().setBooleanValue(GTConfig.PREF_AUTO_LOGIN, false);
            }
            GTConfig.instance().isFromLogin = false;
            GTConfig.instance().mUserPwd = "";
            mPresenter.isLoading = false;
            mPresenter.setPresenterImpl(null);
            mPresenter = null;
        }
        if (null != mSwitchPresenter) {
            mSwitchPresenter.clearData();
            mSwitchPresenter = null;
        }
    }

}
